package com.fire.user.util.wx.wxPush;

import com.fire.user.util.wx.HttpsUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;

@Component
public class TokenUtil {

	private static Logger log = LoggerFactory.getLogger(TokenUtil.class);
	@Value("${weChat.accessTokenUrl}")
	private String accessTokenUrl;
	@Autowired
	private HttpsUtil httpsUtil;

	/**
	 * 获得微信 AccessToken access_token是公众号的全局唯一接口调用凭据，公众号调用各接口时都需使用access_token。
	 * 开发者需要access_token的有效期目前为2个小时，需定时刷新，重复获取将导致上次获取 的access_token失效。
	 * （此处我是把token存在Redis里面了）
	 */
	public AccessToken getWXToken(String appId, String appSecret) {

		/*
		 * String appId="wxe31ff8970aa541bd"; String
		 * appSecret="9267fb4619591d492362f0037b80148a";
		 */
		String tokenUrl = accessTokenUrl + "&appid=" + appId
				+ "&secret=" + appSecret;
		JSONObject jsonObject = httpsUtil.httpsRequest(tokenUrl, "GET", null);
		// String token=jsonObject.getString("access_token");
		AccessToken access_token = new AccessToken();
		log.info("获取的token的值:" + access_token);
		if (null != jsonObject) {
			try {
				access_token.setAccessToken(jsonObject.getString("access_token"));
				access_token.setExpiresin(jsonObject.getInteger("expires_in"));
			} catch (JSONException e) {
				access_token = null;
				// 获取token失败
				log.error("获取token失败 errcode:{} errmsg:{}", jsonObject.getInteger("errcode"),
						jsonObject.getString("errmsg"));
			}
		}

		return access_token;
	}
}
